package com.chaofan.sell.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * cookie工具类
 *
 * @author Fairy
 * @date 2021/11/3
 */
public class CookieUtil {

    /**
     * 设置cookie
     *
     * @param response 需要设置的response
     * @param name     cookie名
     * @param value    cookie值
     * @param maxAge   过期时间
     */
    public static void set(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public static void set(HttpServletResponse response, String name, String value) {
        set(response, name, value, 7200);
    }

    /**
     * 获取cookie值
     *
     * @param request 需要获取的请求
     * @param name    cookie name
     * @return cookie value
     */
    public static Cookie get(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = array2CookieMap(request);
        if (cookieMap.containsKey(name)) {
            return cookieMap.get(name);
        }
        return null;
    }

    /**
     * cookie数组转map
     *
     * @param request 待处理request
     * @return cookie map
     */
    private static Map<String, Cookie> array2CookieMap(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
//        assert cookies != null && cookies.length > 0;
        Map<String, Cookie> cookieMap = new HashMap<>(cookies.length);
        for (var cookie : Objects.requireNonNull(cookies)) {
            cookieMap.put(cookie.getName(), cookie);
        }
        return cookieMap;
    }
}
